<template>
  <!--新增/编辑-->
  <el-dialog
    :close-on-click-modal="false"
    title="新增客诉"
    :beforeClose="handleClose2"
    :visible.sync="dialogVisible2"
    width="500px">
    <el-menu :default-active="form.applyType" class="el-menu-demo" mode="horizontal" @select="handleSelect" style="margin-top: -20px">
      <el-menu-item index="诉求">诉求</el-menu-item>
      <el-menu-item index="售后">售后</el-menu-item>
    </el-menu>
    <el-form :model="form" size="mini" label-width="120px" :rules="rules" ref="form" style="margin-top: 20px">

      <el-form-item label="客户名称：" v-if="popType=='noItem'" prop="customerId">
        <el-select
          @change="changeCustomerId"
          clearable
          v-model="form.customerId"
          filterable
          remote
          reserve-keyword
          placeholder="请输入关键词"
          :remote-method="remoteMethod1"
          :loading="customerLoading">
          <el-option
            v-for="item in customerList"
            :key="item.customerId"
            :label="item.customerName"
            :value="item.customerId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="客户名称：" v-else>
        {{form.customerName}}
      </el-form-item>
      <el-form-item label="诉求类型：" prop="applyReason" v-if="form.applyType=='诉求'">
        <el-select  v-model="form.applyReason">
          <el-option :value="item" :label="item" :key="item" v-for="item in option1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="售后类型：" prop="applyReason" v-else>
        <el-select  v-model="form.applyReason">
          <el-option :value="item" :label="item" :key="item" v-for="item in option3"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="关联订单：" prop="orderSn" v-if="popType == 'noOrderId' || popType == 'noItem'">
        <el-select v-model="form.orderSn" filterable clearable @change="changeOrderSn">
          <el-option :label="item.orderSn" v-for="item in orderList" :value="item.orderSn" :key="item.orderSn"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="关联订单：" v-else>
        {{form.orderSn}}
      </el-form-item>
      <el-form-item label="诉求内容：" v-if="form.applyType=='诉求'" prop="applyRemark">
        <el-input v-model="form.applyRemark" type="textarea" :rows="2"></el-input>
      </el-form-item>
      <el-form-item label="售后内容：" v-else-if="form.applyType=='售后'" prop="applyRemark">
        <el-input v-model="form.applyRemark" type="textarea" :rows="2"></el-input>
      </el-form-item>
      <el-form-item label="关联金额：" v-if="form.applyType=='售后'" prop="relationAmount">
        <el-input v-model="form.relationAmount" type="number" style="width:193px"></el-input>
      </el-form-item>
      <el-form-item label="责任归属：" v-if="form.applyType=='售后'" prop="dutyParty">
        <el-select  v-model="form.dutyParty">
          <el-option :value="item" :label="item" :key="item" v-for="item in option4"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="处理方案：" prop="handleType">
        <el-select  v-model="form.handleType" v-if="form.applyType=='诉求'">
          <el-option :value="item" :label="item" :key="item" v-for="item in option2"></el-option>
        </el-select>
        <el-select  v-model="form.handleType" v-else>
          <el-option :value="item" :label="item" :key="item" v-for="item in option5"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="补偿金额：" prop="payAmount" v-if="form.handleType == '金额补偿'">
          <el-input v-model="form.payAmount" style="width:193px" type="number" ></el-input>
      </el-form-item>
      <el-form-item label="紧急程度：" prop="urgencyType">
        <el-select  v-model="form.urgencyType">
          <el-option value="紧急" label="紧急"></el-option>
          <el-option value="普通" label="普通"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="附件（最多5份）：" >
        <el-upload action="https://upload.qiniup.com" :http-request="sliderRequest" :limit="5" :file-list="form.applyFiles" :on-exceed="onExceed" :on-remove="onRemove" :on-preview="preview">
          <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose2">取 消</el-button>
        <el-button type="primary" @click="handleConfirm2" :loading="btnLoading2">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
import {getCustomerSetting,getCustomerOption,getQiniuToken} from '@/api/partner'
import {developCustomerOrders,developAfterSaleAdd,getCustomerInfoAPI,afterSaleAdd} from '@/api/company'
import {validatePhone} from '@/utils/validate';
import {formatDate} from '@/utils/date';
import store from '@/store'
import { mapGetters } from 'vuex'
import axios from "axios";

const defaultForm = {
  applyId:'',
  "orderSn":"",
  "customerId" : '',
  "applyType" : "诉求", //申请类型(诉求、售后)
  "applyReason" : "", //诉求类型/售后类型
  "applyRemark" : "", //内容
  "applyFiles" : [], //申请附件
  "urgencyType" : "", //紧急程度(紧急/普通)
  "relationAmount" : '', //关联金额
  "dutyParty" : "", //责任归属方
  "handleType" : "",  //处理方案
  payAmount:'',
};
export default {
  name: "index",
  data(){

    return {
      dialogVisible2:false,
      title2:'',
      btnLoading2:false,
      form:JSON.parse(JSON.stringify(defaultForm)),
      rules:{
        customerId:[{required: true, message: '此项必填', trigger: 'change'},],
        orderSn:[{required: false , message: '此项必填', trigger: 'change'},],
        applyReason:[{required: true, message: '此项必填', trigger: 'change'},],
        urgencyType:[{required: true, message: '此项必填', trigger: 'change'},],
        relationAmount:[{required: true, message: '此项必填', trigger: 'change'},],
        dutyParty:[{required: true, message: '此项必填', trigger: 'change'},],
        handleType:[{required: true, message: '此项必填', trigger: 'change'},],
        applyRemark:[{required: true, message: '此项必填', trigger: 'change'},],
        payAmount:[{required: true, message: '此项必填', trigger: 'blur'}]

      },
      goodsList:[],
      uploadToken:{
        token:'',
      },
      imgDomain:'',
      popType:'',
      customerLoading:false,
      customerList:[],
      orderList:[],
      applyReasonList:[],


      option1:[],
      option2:[],
      option3:[],
      option4:[],
      option5:[]
    }
  },
  computed: {
    ...mapGetters([
      'name',
      'mobile',
      'userId'
    ]),
  },
  components : {

  },
  watch: {
    'form.applyType' (val) {
      if(val == '售后') {
        this.$set(this.rules.orderSn[0], 'required', true)
      }else {
        this.$set(this.rules.orderSn[0], 'required', false)

      }

    }
  },
  created() {

  },
  filters: {

  },
  methods:{
    changeCustomerId(){
      this.form.orderSn = ''
      this.getOrder()
    },
    //获取下拉项选
    getOptionList(){
      //诉求类型
      getCustomerInfoAPI({tab:12}).then((res)=>{
         this.option1 = res
      })
      //诉求处理方案
      getCustomerInfoAPI({tab:13}).then((res)=>{
        this.option2 = res
      })
      //售后类型
      getCustomerInfoAPI({tab:14}).then((res)=>{
        this.option3 = res
      })
      //售后责任归属
      getCustomerInfoAPI({tab:15}).then((res)=>{
        this.option4 = res
      })
      //售后处理方案
      getCustomerInfoAPI({tab:16}).then((res)=>{
        this.option5 = res
      })
    },
    handleSelect(key){
      console.log("9999999999")
      this.form.applyType = key
      this.form.applyReason = ''
      this.form.handleType = ''
      this.form.relationAmount = ''
      this.form.dutyParty = ''
    },
    //获取客户列表
    remoteMethod1(query) {
      if(query && query!= ''){
        this.customerLoading = true;
        getCustomerOption({keywords:query,tab:'my'}).then(response => {
          this.customerList = response;
          this.customerLoading = false;
        }).catch(()=>{
          this.customerLoading = false;
        });
      }
    },

    //获取客户配置
    getCustomerSettingList(){
      getCustomerSetting().then((res)=>{
        res.forEach((el)=>{
          if(el.cdtCode == 'after_sale_reason'){
            this.applyReasonList = el.data
          }
        });
      })
    },

    //切换合同
    changeOrderSn(){
      let curItem = this.orderList.find((el)=>{
        return el.orderSn == this.form.orderSn
      })
      this.goodsList = curItem.ordGoodsList
    },

    //获取七牛TOKEN
    getUploadToken(){
      getQiniuToken().then((res)=>{
        this.uploadToken.token = res.token;
        this.imgDomain = res.domain
      })
    },

    onExceed(){
      this.$message.error('最多上传5份文件');
    },

    onRemove(file, fileList){
      this.form.applyFiles = fileList
    },

    //上传文件重写
    sliderRequest(upload) {
      // 文件上传自行处理上传
      // 创建FormData对象 添加相关上传参数
      const formData = new FormData()
      // 文件对象
      formData.append('file', upload.file)
      // key 文件名处理，这样的话七牛会识别文件时什么类型
      let timestamp=new Date().getTime();
      let fileName = timestamp + upload.file.name
      formData.append('key', fileName)
      // token
      formData.append('token', this.uploadToken.token)//这个postData,要在data数据里面进行定义的，，，我这里调接口使用的是vue的方式
      // 上传文件
      // onUploadProgress 查看axios文档 https://github.com/axios/axios
      axios.post("https://upload.qiniup.com", formData, {
        onUploadProgress: (event) => {
          // 监听上传进度
          event.percent = event.loaded / event.total * 100
          upload.onProgress(event)
        }
      }).then((response) => {
        if (response.status === 200) {
          let res = response.data;
          this.form.applyFiles.push({name:this.imgDomain+res.key,url:this.imgDomain+res.key})
        }else{
          this.$message.error('上传失败');
        }
      }).catch((err) => {
        // 调用组件上传失败方法
        this.$message.error('上传失败');
      })
    },


    preview(file){
      window.open(file.url)
    },

    //显示
    showPop(item,applyType){
      this.dialogVisible2 = true;
      this.form = JSON.parse(JSON.stringify(defaultForm));
      if(!item){
        this.popType = 'noItem'
        this.form.applyType = applyType
      }else{
        this.form.customerName = item.customerName;
        this.form.customerId = item.customerId;
        if(item.orderId){
          console.log("item",item)
          this.popType = 'hasOrderId';
          this.form.orderSn = item.orderSn;
        }else if(item.applyId){
          this.popType = 'edit';
          for(let key in defaultForm){
            this.form[key] = item[key] ? item[key] : defaultForm[key]
          }
          this.form.applyFiles = []
          item.applyFiles.forEach((el)=>{
            this.form.applyFiles.push({name:el,url:el})
          })
          this.getOrder()
        }else{
          this.popType = 'noOrderId';
          this.getOrder()
        }
      }

      this.getUploadToken();
      this.getCustomerSettingList();
      this.getOptionList();
    },

    //获取合同列表
    getOrder(){
      if(this.form.customerId){
        developCustomerOrders({customerId:this.form.customerId}).then((res)=>{
          this.orderList = res
        })
      }

    },

    //关闭弹窗
    handleClose2(){
      this.$refs.form.clearValidate();
      this.dialogVisible2 = false;
      this.btnLoading2 = false;
    },

    //提交
    handleConfirm2(){
      this.$refs.form.validate((valid) => {
        let data = JSON.parse(JSON.stringify(this.form));
        if (valid) {
          this.btnLoading2 = true;
          let data = JSON.parse(JSON.stringify(this.form));
          data.applyFiles = data.applyFiles.map(item => item.url).join(",")
          if(data.handleType != '金额补偿'){
            data.payAmount = ''
          }
          afterSaleAdd(data).then((res)=>{
            this.btnLoading2 = false;
            this.handleClose2();
            this.$emit('getList');
          }).catch(()=>{
            this.btnLoading2 = false;
          })
        }
      })
    },
  },
}
</script>

<style  lang="scss">
.avatar-uploader{
  margin-bottom:10px;
  display: inline-block;
  width:80px;
  height:80px;
  border:1px solid #DCDFE6;
  text-align: center;
  line-height: 80px;
  vertical-align: middle;
}
</style>
